<template>
  <div>
    <px-row style="height: 64px">
      <px-col :span="24" class="water_col">
        <div class="waterdom borderRidus">
          <px-form ref="queryRef" style="margin-left: 273px" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
            <px-form-item label="统计维度">
              <px-select v-model="queryParams.timeUnit" placeholder="请选择" style="width: 210px" filterable @change="timechange">
                <px-option v-for="dict in dimensionList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>

            <px-form-item v-if="queryParams.timeUnit == 'YEAR'" label="年份">
              <!-- <px-date-picker v-model="queryParams.Time" type="year" placeholder="请选择" /> -->
              <yearPicker :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </px-form-item>
            <px-form-item v-if="queryParams.timeUnit == 'MONTH'" label="时间">
              <px-date-picker
                v-model="dateRange"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                placeholder="请选择"
                format="YYYY-MM"
                value-format="YYYY-MM"
                @change="settime"
              />
            </px-form-item>
            <px-form-item v-if="queryParams.timeUnit == 'DAY'" label="时间" style="width: 274px !important">
              <px-date-picker
                v-model="dateRange2"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="请选择"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="settime2"
              />
            </px-form-item>

            <px-form-item label="系统" style="width: 270px !important">
              <px-select v-model="queryParams.systemCode" placeholder="请选择" style="width: 220px" filterable @change="getchartsValue">
                <px-option v-for="dict in consumptionSystemList" :key="dict.value" :label="dict.name" :value="dict.value" />
              </px-select>
            </px-form-item>
            <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery()">查询</px-button>
            <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
          </px-form>
        </div>
      </px-col>
    </px-row>
    <px-row style="margin-top: 16px" :gutter="16">
      <px-col :span="12" class="water_col" style="margin-bottom: 16px">
        <div class="waterdom borderRidus boxShadow" style="position: relative; height: 342px">
          <modelTitle title="相关度分析" />
          <px-select
            v-model="firstCode"
            placeholder="请选择"
            style="position: absolute; top: 16px; right: 16px; width: 200px"
            filterable
            @change="firstchange"
          >
            <px-option v-for="dict in hotcodeList" :key="dict.measureCode" :label="dict.measureName" :value="dict.measureCode" />
          </px-select>
          <hotChartContainer
            v-if="hotcodeList"
            :forecastlist="forecastValue"
            :forecast="forecast"
            :spcChartsList="spcChartsList"
            :chartlist="barchartvalue"
            style="width: 100%; height: 280px"
            :width="'100%'"
            :height="'280px'"
            :thermalMapData="thermalMapData"
          />
          <div v-else>
            <px-empty :image-size="200" />
          </div>
        </div>
      </px-col>
      <px-col :span="12" class="water_col" style="margin-bottom: 16px">
        <div class="waterdom borderRidus boxShadow" style="position: relative; height: 342px">
          <modelTitle title="化学品用量分析" />
          <div style="position: absolute; top: 16px; right: 16px">
            <px-select
              v-model="Materialvalue"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
              style="width: 130px; margin-right: 10px"
              clearable
              @change="getchartsValue2"
            >
              <px-option v-for="dict in consumptionMaterialList" :key="dict.value" :label="dict.name" :value="dict.value" />
            </px-select>
            <px-select
              v-model="Spcvalue"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
              style="width: 130px; margin-right: 10px"
              clearable
              @change="showSpc"
            >
              <px-option v-for="dict in codeList" :key="dict.value" :label="dict.measureName" :value="dict.measureCode" />
            </px-select>
            <px-select
              v-model="selectedList"
              class="xginput"
              multiple
              filterable
              placeholder="相关指标"
              style="width: 220px"
              collapse-tags
              collapse-tags-tooltip
              clearable
              @change="showSpc"
            >
              <px-option v-for="(item, index) in spcListselect" :key="index" :label="item.indicatorName" :value="item.point" />
            </px-select>
          </div>

          <!-- <px-checkbox-group v-model="Materialvalue" style="float: left; margin: 16px 0 0 16px">
            <px-checkbox v-for="item in consumptionMaterialList" :key="item.value" :label="item.value" @change="getchartsValue2">{{
              item.name
            }}</px-checkbox>
          </px-checkbox-group> -->

          <!-- <px-checkbox-group v-model="Spcvalue" style="float: left; margin: 16px 0 0 16px">
            <px-checkbox v-for="item in codeList" :key="item.value" :label="item.measureCode" @change="showSpc">{{
              item.measureName
            }}</px-checkbox> </px-checkbox-group
          > -->

          <chartloadSummaryspc
            :forecastlist="forecastValue"
            :forecast="forecast"
            :spcChartsList="spcChartsList"
            :pointspcList="pointspcList"
            :chartlist="barchartvalue"
            style="width: 100%; height: 280px"
            :width="'100%'"
            :height="'280px'"
            :chartsTitle="'化学品用量分析'"
            :startTime="queryParams.startTime"
            :endTime="queryParams.endTime"
          />
        </div>
      </px-col>
    </px-row>
    <px-row :gutter="16">
      <px-col :span="24" class="water_col" style="margin-bottom: 16px">
        <div class="waterdom borderRidus boxShadow">
          <modelTitle title="模拟分析" />
          <px-row :gutter="16">
            <px-col v-loading="moniloading" element-loading-text="模拟分析中..." :span="12">
              <simulationAnalysis
                :forecastlist="forecastValue"
                :forecast="forecast"
                :spcChartsList="spcChartsList"
                :pointspcList="pointspcList"
                :chartlist="SimulationAnalysisList"
                style="width: 100%; height: 280px"
                :width="'100%'"
                :height="'280px'"
                :chartsTitle="'模拟分析'"
                :startTime="queryParams.startTime"
                :endTime="queryParams.endTime"
              />
            </px-col>
            <px-col :span="12" style="position: relative; padding-top: 16px; padding-bottom: 56px; border: 1px solid #dfdfdf">
              <px-form ref="detailruleFormRef" :model="addForm" :inline="true" label-width="120px">
                <px-row style="border-bottom: 1px solid #dfdfdf">
                  <px-col :span="10">
                    <px-form-item style="width: 400px !important" label="模拟变量">
                      <px-select v-model="addForm.param" collapse-tags collapse-tags-tooltip placeholder="请选择" style="width: 200px" clearable>
                        <px-option v-for="dict in addForm.mapParam" :key="dict.fixedParam" :label="dict.name" :value="dict.fixedParam" />
                      </px-select>
                    </px-form-item>
                  </px-col>
                  <px-col :span="6">
                    <px-input v-model="addForm.min" style="width: 80px" placeholder="变量范围" clearable />
                    <span>~</span>
                    <px-input v-model="addForm.max" style="width: 80px" placeholder="变量范围" clearable />
                  </px-col>
                  <px-col :span="6">
                    <px-input v-model="addForm.splitSte" style="width: 180px" placeholder="步数" clearable />
                  </px-col>
                  <px-col
                    v-for="(item, index) in addForm.mapParam.filter(item => item.fixedParam != addForm.param)"
                    :key="index"
                    :span="12"
                    style="padding-left: 52px; margin-bottom: 16px"
                  >
                    <div>
                      <span class="SPCspan">{{ item.name }}</span>
                      <px-input v-model="item.fixedParamValue" style="width: 100px; margin-right: 10px" placeholder="请输入" clearable />
                      <!-- <span class="SPCbtn">获取当前值</span> -->
                      <px-button link type="primary" @click="getSpcValue(item)">
                        <px-tooltip class="box-item" content="获取当前值" placement="top">
                          <px-icon :size="16"><Chart /></px-icon></px-tooltip
                      ></px-button>
                    </div>
                  </px-col>
                </px-row>

                <px-button class="startBtn" type="primary" @click="moni">开始模拟</px-button>
              </px-form>
            </px-col>
          </px-row>
        </div>
      </px-col>
    </px-row>
  </div>
</template>
<script setup lang="ts">
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import chartswwt from "./components/chartswwt.vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import chartloadSummaryspc from "./chartloadSummaryspc.vue";
import simulationAnalysis from "./simulationAnalysis.vue";
import { getToken } from "@/utils/auth";
import type { TableColumnCtx } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import hotChartContainer from "./hotChartContainer.vue";
import { spcqueryList, spcquerySpcAnalysis } from "@/api/spc";
import { PxMessage, PxMessageBox } from "px-ui";
import {
  consumptionqueryConsumptionList,
  consumptionqueryDetail,
  consumptionqueryMaterialList,
  consumptionquerySystemList,
  chemicalqueryFuture,
  consumptionqueryMeasureList,
  consumptionqueryHeatMapList,
  algorithmSpecialSimulationAnalysis,
  algorithmSpecialSimulationAnalysisTaskId
} from "@/api/waterconsumption";
import { querySpecValues } from "@/api/machineApi";
import { algorithmcorrelationFactor, algorithmcacheRedis, algorithmcorrelationFactorWater, algorithmcacheRedisWater } from "@/api/spc";
const dateValue = ref<any>({ startYear: new Date().getFullYear() - 6, endYear: new Date().getFullYear() });
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  // queryParams.value.dateRange = [startYear.toString(), endYear.toString()];
  queryParams.value.startTime = `${startYear}-01-01 00:00:00`;
  queryParams.value.endTime = `${endYear}-12-31 23:59:59`;
};
const settime = val => {
  console.log(val);
  queryParams.value.startTime = `${val[0]}-01 00:00:00`;
  queryParams.value.endTime = `${val[1]}-31 23:59:59`;
};
const selectedList = ref([]);
const timechange = val => {
  if (val == "MONTH") {
    queryParams.value.startTime = `${dateRange.value[0]}-01-01 00:00:00`;
    queryParams.value.endTime = `${dateRange.value[1]}-12-31 23:59:59`;
  }
  if (val == "YEAR") {
    queryParams.value.startTime = `${dateValue.value.startYear}-01-01 00:00:00`;
    queryParams.value.endTime = `${dateValue.value.endYear}-12-31 23:59:59`;
  }
  if (val == "DAY") {
    queryParams.value.startTime = `${dateRange2.value[0]}-01 00:00:00`;
    queryParams.value.endTime = `${dateRange2.value[1]}-31 23:59:59`;
  }
};
const firstCode = ref("");
const firstchange = val => {
  getthermalMapuuid();
};
const getSpcValue = item => {
  console.log(item);
  querySpecValues([item.fixedParam]).then(res => {
    item.fixedParamValue = res.rows[0].last_value;
  });
};
const forecastValue = ref([]);
const spcListselect = ref([]);
const settime2 = val => {
  console.log(val);
  queryParams.value.startTime = val[0];
  queryParams.value.endTime = val[1];
};
const data = reactive({
  forecast: false,
  spcName: "",
  barchartvalue: {},
  thermalMapData: {
    xaxis: [],
    yaxis: [],
    xyData: [],
    correlationList: []
  },
  consumptionMaterialList: [],
  consumptionSystemList: [],
  Materialvalue: [],
  Systemvalue: "",
  fsconsumptionMaterialList: [],
  fsconsumptionSystemList: [],
  fsMaterialvalue: "",
  fsSystemvalue: "",
  chartsTitle: "化学品消耗趋势图",
  queryParams: {
    timeUnit: "DAY",
    startTime: "",
    endTime: "",
    consumptionType: "",
    systemCode: "",
    materialCode: []
  },
  syetemList: [],
  samplingLocationList: [],
  dateRange: [],
  dateRange2: [],
  testItemList: [],
  chartsList: [],
  tableData: {},
  dimensionList: [
    {
      itemName: "日",
      itemValue: "DAY"
    }
    // {
    //   itemName: "月",
    //   itemValue: "MONTH"
    // },
    // {
    //   itemName: "年",
    //   itemValue: "YEAR"
    // }
  ],
  spcList: [],
  spcChartsList: [],
  systemList: [],
  hotcodeList: [],
  addForm: {
    mapParam: [],
    systemValue: "",
    param: "",
    min: null,
    max: null,
    paramValue: "2~4",
    splitSte: null
  }
});
const {
  addForm,
  hotcodeList,
  thermalMapData,
  forecast,
  systemList,
  spcChartsList,
  spcName,
  spcList,
  barchartvalue,
  Materialvalue,
  Systemvalue,
  consumptionMaterialList,
  consumptionSystemList,
  fsMaterialvalue,
  fsSystemvalue,
  fsconsumptionMaterialList,
  fsconsumptionSystemList,
  queryParams,
  chartsTitle,
  tableData,
  dateRange,
  dimensionList,
  dateRange2
} = toRefs(data);
const activeWater = ref("pure");
const tabDisabled = ref(false);
const tabPaneList = [
  {
    label: "纯水",
    name: "pure"
  },
  {
    label: "废水",
    name: "waste"
  }
];
const radio = ref("时");

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];

const getqueryCategoryList = () => {
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 100);
  dateRange.value = [formatDate(start), formatDate(end)];
};
const getsixmonth = () => {
  const date = new Date();
  let SixMon = new Date(date);
  SixMon.setMonth(SixMon.getMonth() - 6);
  console.log(SixMon.toISOString().split("T")[0].slice(0, -3));
  return SixMon.toISOString().split("T")[0].slice(0, -3);
};
const getdate = () => {
  const date = new Date();
  return date.toISOString().split("T")[0].slice(0, -3);
};
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}

onMounted(() => {
  consumptionquerySystemList({
    consumptionType: "chemicalUPW"
  }).then(res => {
    console.log(res);
    consumptionSystemList.value = res;
    Systemvalue.value = res[0].value;
    queryParams.value.systemCode = res[0].value;
    setstarttime();
    spcqueryList({
      indicatorName: "",
      classCode: "WATER",
      systemCode: [],
      indicatorLevel: "",
      startTime: dateRange2.value[0],
      endTime: dateRange2.value[1],
      point: "",
      querySpcCount: false,
      pageNum: 1,
      pageSize: 9999
    }).then(res => {
      spcListselect.value = res.data;
    });
    getchartsValue();
    getList();
  });
});

const setstarttime = () => {
  dateRange.value = [`${getsixmonth()}`, `${getdate()}`];
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
  dateRange2.value = [formatDate(start), formatDate(end)];
  queryParams.value.timeUnit = "DAY";
};
const changeplanCode = () => {
  setcheckList();
};
const setcheckList = () => {
  let timePeriodvalue = "";
  if (queryParams.value.timeUnit == "DAY") {
    timePeriodvalue = "day";
  }
  if (queryParams.value.timeUnit == "MONTH") {
    timePeriodvalue = "months";
  } else {
    PxMessage.warning("指标不支持年度搜索");
    return false;
  }
  spcquerySpcAnalysis({
    jobIdList: [spcName.value],
    timePeriod: timePeriodvalue,
    startTime: queryParams.value.timeUnit == "DAY" ? `${dateRange.value.value2[0]}-01 00:00:00` : `${dateRange.value[0]}-01 00:00:00`,
    endTime: queryParams.value.timeUnit == "DAY" ? `${dateRange.value[1]}-31 00:00:00` : `${dateRange.value[1]}-31 00:00:00`
  }).then((response: any) => {
    console.log(response);
    spcChartsList.value = response;
  });
};
const getcharts = val => {
  console.log(activeWater.value);
  tabDisabled.value = true;
  if (activeWater.value == "pure") {
    consumptionquerySystemList({
      consumptionType: "chemicalUPW"
    }).then(res => {
      console.log(res);
      consumptionSystemList.value = res;
      Systemvalue.value = res[0].value;
      queryParams.value.systemCode = res.map(item => item.value);
      consumptionqueryMaterialList({
        consumptionType: "chemicalUPW",
        systemCode: queryParams.value.systemCode
      }).then(res => {
        console.log(res);
        consumptionMaterialList.value = res;
        queryParams.value.materialCode = res.map(item => item.value);
        Materialvalue.value = res.map(item => item.value);

        setstarttime();
      });
    });
    setTimeout(() => {
      getchartsValue();
    }, 1000);
  } else {
    consumptionquerySystemList({
      consumptionType: "chemicalUPW"
    }).then(res => {
      console.log(res);
      consumptionSystemList.value = res;
      Systemvalue.value = res[0].value;
      queryParams.value.systemCode = res.map(item => item.value);
      consumptionqueryMaterialList({
        consumptionType: "chemicalUPW",
        systemCode: queryParams.value.systemCode
      }).then(res => {
        console.log(res);
        consumptionMaterialList.value = res;
        queryParams.value.materialCode = res.map(item => item.value);
        Materialvalue.value = res.map(item => item.value);

        setstarttime();
      });
    });
    setTimeout(() => {
      getchartsValue();
    }, 1000);
  }
  setTimeout(() => {
    getList();
  }, 100);
  setTimeout(() => {
    getchartsValue();
  }, 1000);
};
const pointspcList = ref([]);
const showSpc = () => {
  console.log(Spcvalue.value);

  console.log(selectedList.value);
  if ([...Spcvalue.value, ...selectedList.value].length > 0) {
    spcquerySpcAnalysis({
      pointList: [...Spcvalue.value, ...selectedList.value],
      timePeriod: "day",
      startTime: dateRange2.value[0],
      endTime: dateRange2.value[1]
    }).then(res => {
      console.log(res);
      pointspcList.value = res;
    });
  } else {
    pointspcList.value = [];
  }
};
const getchartsValue2 = () => {
  if (activeWater.value == "pure") {
    consumptionqueryDetail({
      timeUnit: queryParams.value.timeUnit,
      startTime: dateRange2.value[0],
      endTime: dateRange2.value[1],
      consumptionType: "chemicalUPW",
      systemCode: queryParams.value.systemCode,
      materialCode: Materialvalue.value
    })
      .then(res => {
        console.log(res);
        barchartvalue.value = res;
        tabDisabled.value = false;
      })
      .catch(() => {
        tabDisabled.value = false;
      });
  } else {
    consumptionqueryDetail({
      timeUnit: queryParams.value.timeUnit,
      startTime: dateRange2.value[0],
      endTime: dateRange2.value[1],
      consumptionType: "chemicalUPW",
      systemCode: queryParams.value.systemCode,
      materialCode: Materialvalue.value
    })
      .then(res => {
        console.log(res);
        barchartvalue.value = res;
        tabDisabled.value = false;
      })
      .catch(() => {
        tabDisabled.value = false;
      });
  }
};
const getchartsValue = () => {
  selectedList.value = [];
  Spcvalue.value = [];
  firstCode.value = "";
  if (activeWater.value == "pure") {
    consumptionqueryMaterialList({
      consumptionType: "chemicalUPW",
      systemCode: [queryParams.value.systemCode]
    }).then(res => {
      console.log(res);
      consumptionMaterialList.value = res;
      Materialvalue.value = res.map(item => item.value);
      consumptionqueryDetail({
        timeUnit: queryParams.value.timeUnit,
        startTime: dateRange2.value[0],
        endTime: dateRange2.value[1],
        consumptionType: "chemicalUPW",
        systemCode: queryParams.value.systemCode,
        materialCode: Materialvalue.value
      })
        .then(res => {
          console.log(res);
          barchartvalue.value = res;
          tabDisabled.value = false;
        })
        .catch(() => {
          tabDisabled.value = false;
        });
      setstarttime();
    });
  } else {
    consumptionqueryDetail({
      timeUnit: queryParams.value.timeUnit,
      startTime: queryParams.value.startTime,
      endTime: queryParams.value.endTime,
      consumptionType: queryParams.value.consumptionType,
      systemCode: fsSystemvalue.value,
      materialCode: fsMaterialvalue.value
    })
      .then(res => {
        console.log(res);
        barchartvalue.value = res;
        tabDisabled.value = false;
      })
      .catch(() => {
        tabDisabled.value = false;
      });
  }
  showSpc();
};
const loading = ref(false);
const handleQuery = () => {
  getList();
  setTimeout(() => {
    // getchartsValue();
  }, 1000);
};
const resetQuery = () => {
  consumptionquerySystemList({
    consumptionType: "chemicalUPW"
  }).then(res => {
    console.log(res);
    consumptionSystemList.value = res;
    Systemvalue.value = res[0].value;
    queryParams.value.systemCode = res[0].value;
    setstarttime();
    spcqueryList({
      indicatorName: "",
      classCode: "WATER",
      systemCode: [],
      indicatorLevel: "",
      startTime: dateRange2.value[0],
      endTime: dateRange2.value[1],
      point: "",
      querySpcCount: false,
      pageNum: 1,
      pageSize: 9999
    }).then(res => {
      spcListselect.value = res.data;
    });
    getchartsValue();
    getList();
  });
};
interface SummaryMethodProps<T = Product> {
  columns: TableColumnCtx<T>[];
  data: T[];
}
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "总计";
      return;
    } else {
      sums[index] =
        `${data
          .map(item => item.actualList[index - 1])
          .reduce((prev, curr) => {
            const value = Number(curr);
            if (!Number.isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0)}` != "0"
          ? `${data
              .map(item => item.actualList[index - 1])
              .reduce((prev, curr) => {
                const value = Number(curr);
                if (!Number.isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
              .toFixed(2)}`
          : "N/A";
    }
    //   if (index % 2 !== 0) {
    //   sums[index] =
    //     `${data
    //       .map(item => item.actualList[(index - 1) / 2])
    //       .reduce((prev, curr) => {
    //         const value = Number(curr);
    //         if (!Number.isNaN(value)) {
    //           return prev + curr;
    //         } else {
    //           return prev;
    //         }
    //       }, 0)}` != "0"
    //       ? `${data
    //           .map(item => item.actualList[(index - 1) / 2])
    //           .reduce((prev, curr) => {
    //             const value = Number(curr);
    //             if (!Number.isNaN(value)) {
    //               return prev + curr;
    //             } else {
    //               return prev;
    //             }
    //           }, 0)}`
    //       : "N/A";
    // }
    // else if (index % 2 === 0) {
    //   sums[index] =
    //     `${data
    //       .map(item => item.predictiveList[index / 2])
    //       .reduce((prev, curr) => {
    //         const value = Number(curr);
    //         if (!Number.isNaN(value)) {
    //           return prev + curr;
    //         } else {
    //           return prev;
    //         }
    //       }, 0)}` != "0"
    //       ? `${data
    //           .map(item => item.predictiveList[index / 2])
    //           .reduce((prev, curr) => {
    //             const value = Number(curr);
    //             if (!Number.isNaN(value)) {
    //               return prev + curr;
    //             } else {
    //               return prev;
    //             }
    //           }, 0)}`
    //       : "N/A";
    // }
  });
  return sums;
};
const SimulationAnalysisList = ref({});
const TaskId = ref("");
const moniloading = ref(false);
const moni = () => {
  moniloading.value = true;
  console.log(addForm.value);
  let parmas = {
    mapParam: [],
    systemValue: "",
    param: {
      param: "",
      paramValue: "",
      splitSte: 0
    }
  };
  parmas.mapParam = addForm.value.mapParam.map(item => {
    return {
      fixedParam: item.fixedParam,
      fixedParamValue: item.fixedParamValue
    };
  });
  parmas.systemValue = queryParams.value.systemCode;
  parmas.param = {
    param: addForm.value.param,
    paramValue: `${addForm.value.min}~${addForm.value.max}`,
    splitSte: addForm.value.splitSte
  };
  algorithmSpecialSimulationAnalysisTaskId(parmas)
    .then(res => {
      console.log(res);
      if (res != null) {
        TaskId.value = res;
        getAnalysis();
      }
    })
    .catch(() => {
      moniloading.value = false;
    });
};
const getAnalysis = () => {
  let parmas = {
    mapParam: [],
    systemValue: "",
    param: {
      param: "",
      paramValue: "",
      splitSte: 0
    },
    taskId: ""
  };
  parmas.mapParam = addForm.value.mapParam.map(item => {
    return {
      fixedParam: item.fixedParam,
      fixedParamValue: item.fixedParamValue
    };
  });
  parmas.systemValue = queryParams.value.systemCode;
  parmas.param = {
    param: addForm.value.param,
    paramValue: `${addForm.value.min}~${addForm.value.max}`,
    splitSte: addForm.value.splitSte
  };
  parmas.taskId = TaskId.value;
  algorithmSpecialSimulationAnalysis(parmas)
    .then(res => {
      // SimulationAnalysisList.value = res;
      if (res == null) {
        setTimeout(() => {
          getAnalysis();
        }, 5000);
      } else {
        moniloading.value = false;
        SimulationAnalysisList.value = res;
        console.log(res);
      }
    })
    .catch(() => {
      moniloading.value = false;
    });
};
const thermalMapuuid = ref("");
const thermalflg = ref(false);
const codeList = ref([]);
const Spcvalue = ref([]);
function getList() {
  loading.value = true;
  if (queryParams.value.timeUnit == "MONTH") {
    if (dateRange.value != null) {
      queryParams.value.startTime = `${dateRange.value[0]}-01 00:00:00`;
      queryParams.value.endTime = `${dateRange.value[1]}-31 00:00:00`;
    } else {
      queryParams.value.startTime = "";
      queryParams.value.endTime = "";
    }
  }
  if (queryParams.value.timeUnit == "DAY") {
    if (dateRange.value != null) {
      queryParams.value.startTime = `${dateRange2.value[0]}`;
      queryParams.value.endTime = `${dateRange2.value[1]}`;
    } else {
      queryParams.value.startTime = "";
      queryParams.value.endTime = "";
    }
  }
  consumptionqueryMeasureList({
    consumptionType: "chemicalUPW",
    systemCode: queryParams.value.systemCode
    // consumptionType: "chemicalUPW"
  }).then(res => {
    codeList.value = res;
    let spcList = res;
    if (spcList.length > 0) {
      addForm.value.mapParam = spcList.map(item => {
        return {
          fixedParam: item.measureCode,
          name: item.measureName,
          fixedParamValue: ""
        };
      });
    } else {
      addForm.value.mapParam = [];
    }

    console.log(res);
  });
  consumptionqueryHeatMapList({
    consumptionType: "chemicalUPW",
    systemCode: queryParams.value.systemCode
    // consumptionType: "chemicalUPW"
  }).then(res => {
    hotcodeList.value = res;
    if (res != null) {
      firstCode.value = res[0].measureCode;
    }
    console.log(res);
    getthermalMapuuid();
  });
}
const getthermalMapuuid = () => {
  thermalflg.value = true;
  if (hotcodeList.value != null) {
    let parmas = {
      tagNameList: hotcodeList.value.map(item => item.measureCode),
      startTime: dateRange2.value[0],
      endTime: dateRange2.value[1],
      centerParam: firstCode.value
    };
    algorithmcorrelationFactorWater(parmas)
      .then(res => {
        console.log(res);
        thermalMapuuid.value = res;
        getthermalMapdata();
      })
      .catch(() => {
        thermalflg.value = false;
      });
  }
};
//获取热力图
const getthermalMapdata = () => {
  algorithmcacheRedisWater({
    uuid: thermalMapuuid.value,
    centerParam: firstCode.value
  })
    .then(res => {
      console.log(res);
      if (res == null) {
        setTimeout(() => {
          getthermalMapdata();
        }, 5000);
      } else {
        thermalMapData.value = res;
        thermalflg.value = false;
      }
      // else{
      //    thermalMapData.value = {
      //   xaxis: [],
      //   yaxis: [],
      //   xyData: []
      // };
      // PxMessage({
      //   message: `暂无数据`,
      //   type: "error"
      // });
      // }
    })
    .catch(() => {
      thermalflg.value = false;
      thermalMapData.value = {
        xaxis: [],
        yaxis: [],
        xyData: []
      };
      PxMessage({
        message: `暂无数据`,
        type: "error"
      });
    });
};
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
/** 导出按钮操作 */
function handleExport() {
  if (dateRange.value != null && dateRange.value.length > 0) {
    let Token = getToken().accessToken || "";
    if (queryParams.value.timeUnit == "MONTH") {
      if (dateRange.value != null) {
        queryParams.value.startTime = `${dateRange.value[0]}-01 00:00:00`;
        queryParams.value.endTime = `${dateRange.value[1]}-31 00:00:00`;
      } else {
        queryParams.value.startTime = "";
        queryParams.value.endTime = "";
      }
    }
    if (queryParams.value.timeUnit == "DAY") {
      if (dateRange.value != null) {
        queryParams.value.startTime = `${dateRange2.value[0]}`;
        queryParams.value.endTime = `${dateRange2.value[1]}`;
      } else {
        queryParams.value.startTime = "";
        queryParams.value.endTime = "";
      }
    }
    if (activeWater.value == "pure") {
      queryParams.value.consumptionType = "chemicalUPW";
    } else {
      queryParams.value.consumptionType = "chemicalUPW";
    }
    // proxy.download("post", "/operation/api/v1/water/testQuality/pwMetalImpurity/export", queryParams.value, "水质检测-纯水金属阴阳离子.xlsx");
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E6%25B6%2588%25E8%2580%2597%25E6%258A%25A5%25E8%25A1%25A8.cpt&token=${Token}&from=${queryParams.value.startTime}&to=${queryParams.value.endTime}&consumptionType=${queryParams.value.consumptionType}&timeUnit=${queryParams.value.timeUnit}&format=excel&extype=simple&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}`;
    window.location.href = url;
  } else {
    PxMessage({
      message: "请选择时间后再导出",
      type: "error"
    });
  }
}
</script>

<style scoped lang="scss">
.water_col {
  height: 100%;
}

.waterdom {
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.first_width {
  width: calc(100% - 16px);
}

.model_chart {
  position: relative;
  width: 100%;
  height: calc(100% - 40px);
  margin-top: 10px;

  .co2img {
    position: absolute;
    top: 32px;
    left: 22px;
    width: 32px;
    height: 32px;
  }

  .titlep {
    position: absolute;
    top: 29px;
    left: 70px;
    font-size: 16px;
    font-weight: 400;
    color: #000;
  }

  .titlevalue {
    position: absolute;
    top: 55px;
    left: 70px;

    .titlevalue1 {
      float: left;
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      color: #3b82f6;
    }

    .titlevalue1span {
      font-size: 16px;
      font-weight: 400;
      line-height: 22px;
      color: #4f4f4f;
    }

    .titlevalue2 {
      float: left;
      margin-top: 5px;
      margin-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #f87171;
    }
  }

  .co2mian {
    position: absolute;
    top: 112px;
    left: 0;
    width: 100%;
    height: 92px;
  }

  .co2mianleft {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianleftp {
      width: calc(100% - 21px);
      height: 22px;
      padding-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
      border-right: 1px solid #cbcdd8;
    }
  }

  .co2mianright {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianrightp {
      width: calc(100% - 45px);
      height: 22px;
      padding-left: 45px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }
  }

  .co2mianleftp2 {
    margin-left: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;

    .co2mianleftp2span {
      font-size: 14px;
      font-weight: 400;
      color: #4f4f4f;
    }
  }

  .co2mianleftp3 {
    float: left;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #000;

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #34d399;
    }
  }
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 26px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 16px;
}

.percentage-value2 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}

.percentage-label2 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.percentage-value3 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  color: #f00;
}

.percentage-label3 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #f00;
}

.jindu1 {
  margin: 24px 0 0 17px;
}

.jindu2 {
  margin: 38px calc((100% - 103px) / 2);
}

.jindu1p {
  width: calc(100% - 24px);
  margin-top: 0;
  font-size: 16px;
  text-align: center;
}

.jindu2p {
  width: 100%;
  margin-top: -40px;
  font-size: 14px;
  text-align: center;
}

:deep(.px-table) {
  .px-table__cell {
    padding: 6px 0;
  }

  .px-table__header-wrapper,
  .px-table__fixed-header-wrapper {
    th {
      background-color: #e7eefb !important;
    }
  }
}

.SPCspan {
  display: inline-block;
  width: 96px;
  margin-right: 8px;
  overflow: hidden;
  font-size: 14px;
  line-height: 14px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.SPCbtn {
  font-size: 14px;
  color: #3b82f6;
  cursor: pointer;
}

.startBtn {
  position: absolute;
  bottom: 16px;
  left: calc(50% - 44px);
}

:deep(.xginput) {
  .px-tag--light {
    max-width: 70px !important;
  }
}
</style>
